from tortoise import fields
from tortoise.models import Model
from fastapi import HTTPException


class BaseModel(Model):
    id = fields.UUIDField(pk=True)
    active = fields.BooleanField(null=True, default=True)
    created_at = fields.DatetimeField(auto_now_add=True, null=True)
    updated_at = fields.DatetimeField(auto_now=True, null=True)

    class Meta:
        abstract = True
        ordering = ["-created_at"]  # 添加这一行

    @classmethod
    def get_or_raise(cls, *args, **kwargs):
        obj = cls.get_or_none(*args, **kwargs)
        if not obj:
            raise HTTPException(status_code=404, detail="资源不存在")
        return obj
